extends ParallaxBackground

# 视差背景移动速度
@export var scroll_speed: float = 5.0
# 是否自动滚动
@export var auto_scroll: bool = true
# 相机跟随强度 (0-1)，1为完全跟随相机
@export var camera_influence: float = 0.2

# 上一帧相机的位置
var _last_camera_pos: Vector2 = Vector2.ZERO
# 是否已初始化相机位置
var _camera_initialized: bool = false
# 屏幕尺寸
var _screen_size: Vector2i = Vector2i.ZERO
# 视差层引用
var far_mountains_layer: ParallaxLayer
var mid_mountains_layer: ParallaxLayer
var near_mountains_layer: ParallaxLayer
var hills_layer: ParallaxLayer
var trees_layer: ParallaxLayer
# 所有层数组
var all_layers = []

func _ready():
	# 确保初始状态正确
	_camera_initialized = false
	_screen_size = get_viewport().get_visible_rect().size
	
	# 获取所有层引用
	far_mountains_layer = $FarMountainsLayer
	mid_mountains_layer = $MidMountainsLayer
	near_mountains_layer = $NearMountainsLayer
	hills_layer = $HillsLayer
	trees_layer = $TreesLayer
	
	# 将所有层添加到数组中
	all_layers = [far_mountains_layer, mid_mountains_layer, near_mountains_layer, hills_layer, trees_layer]
	
	# 添加调试信息
	print("视差背景初始化完成")
	print("屏幕尺寸:", _screen_size)
	for layer in all_layers:
		if layer:
			print("层:", layer.name, "motion_scale:", layer.motion_scale)

func _process(delta):
	# 自动滚动背景
	if auto_scroll:
		scroll_offset.x -= scroll_speed * delta
	
	# 处理相机移动导致的视差效果
	var camera = get_viewport().get_camera_2d()
	if camera:
		if not _camera_initialized:
			_last_camera_pos = camera.global_position
			_camera_initialized = true
			return
			
		var camera_delta = camera.global_position - _last_camera_pos
		_last_camera_pos = camera.global_position
		
		# 应用相机移动的影响
		if camera_influence > 0:
			scroll_offset -= camera_delta * camera_influence
